<!-- src/views/PexelsSearch.vue (或者你的原始文件名) -->
<template>
	<div
		class="max-h-screen flex flex-col bg-gray-100 dark:bg-zinc-900 text-gray-800 dark:text-gray-200 p-4"
	>
		<!-- 搜索栏 -->
		<AppHeader @back="handleBack">
			 <template #center>
        <SearchInput
          v-model="searchQuery"
          placeholder="请输入内容"
          @search="handleSearch"
        />
      </template>
		</AppHeader>
		<!-- 使用封装好的瀑布流组件 -->
		<WaterfallList
			:items="pexelsStore.list"
			:is-loading="pexelsStore.isLoading"
			:is-finished="pexelsStore.isFinished"
			:colsMobile="2"
			:get-item-id="item => item.id"
			:get-aspect-ratio="item => item.photoWidth / item.photoHeight"
			@load-more="loadMoreItems"
		>
			<!-- #default 插槽定义了如何渲染每一个 item -->
			<template #default="{ item }">
				<PexelsCard :item="item" />
			</template>

			<!-- (可选) 自定义空状态的显示 -->
			<template #empty>
				<p>
					No results found for "{{ pexelsStore.currentQuery }}". Try
					another search.
				</p>
			</template>
		</WaterfallList>
	</div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useSearchPexelsStore } from "@/store/modules/search_pexels";
import SearchInput from "@/components/SearchInput.vue";
import WaterfallList from "@/components/WaterfallList.vue"; // 引入新组件
import PexelsCard from "./components/PexelsCard.vue"; // PexelsCard 现在在这里引入
import AppHeader from "@/components/AppHeader.vue";

const router = useRouter();
const route = useRoute();
const pexelsStore = useSearchPexelsStore();
const searchQuery = ref<string>("");

// 搜索操作
const handleSearch = () => {
	if (!searchQuery.value.trim()) return;
	// 调用 store 的 loadMore，它内部会处理重置逻辑
	pexelsStore.loadMore(searchQuery.value.trim());
};

// 响应 WaterfallList 组件的 loadMore 事件
const loadMoreItems = () => {
	pexelsStore.loadMore(searchQuery.value.trim());
};

const handleBack = () => {
	router.back();
};

// 监听路由变化来触发搜索
watch(
	() => route.query.q,
	newQuery => {
		const queryStr = ((newQuery as string) || "").trim();
		if (queryStr) {
			searchQuery.value = queryStr;
			// 首次加载或路由驱动的搜索
			pexelsStore.loadMore(queryStr);
		}
	},
	{ immediate: true }
);
</script>
